package com.example.zjhuojback.service;

import com.example.zjhuojback.entity.*;
import com.example.zjhuojback.mapper.ContestMapper;
import com.example.zjhuojback.mapper.ForumMapper;
import com.example.zjhuojback.mapper.ProblemMapper;
import com.example.zjhuojback.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;

@Service
public class ContestService {
    @Autowired
    ContestMapper contestMapper;

    @Autowired
    ProblemMapper problemMapper;

    @Autowired
    UserMapper userMapper;
    /**
     * 查询
     * @param
     * @param
     * @return
     */
    public List<Contest> selectAll() {
        return contestMapper.selectAll();
    }
    public Contest selectById(Integer id) {
        // 查询信息
        Contest dbContest = contestMapper.selectById(id);
        return dbContest;
    }

    /**
     * 添加比赛
     * @param contest
     */
    public void insertContest(Contest contest) {
        contestMapper.insert(contest);
        // 遍历题目列表并插入题目
        List<Problem> questions = contest.getQuestions();
        if (questions != null && !questions.isEmpty()) {
            for (Problem question : questions) {
                // 获取题目的ID和标题
                ContestProblem contestProblem = new ContestProblem();
                contestProblem.setContestId(contest.getId());
                contestProblem.setProblemId(question.getId());
                contestProblem.setProblemTitle(question.getTitle());
                // 插入题目和比赛的关联信息
                contestMapper.insertProblem(contestProblem);
            }
        }
    }

    /**
     * 更新比赛
     * @param contest
     */
    public void updateContest(Contest contest) {
        // 更新比赛的基本信息
        contestMapper.update(contest);
        // 删除原有的题目关联，准备重新添加
        contestMapper.removeProblem(contest.getId());
        // 遍历题目列表并插入题目
        List<Problem> questions = contest.getQuestions();
        if (questions != null && !questions.isEmpty()) {
            for (Problem question : questions) {
                // 获取题目的ID和标题
                ContestProblem contestProblem = new ContestProblem();
                contestProblem.setContestId(contest.getId());
                contestProblem.setProblemId(question.getId());
                contestProblem.setProblemTitle(question.getTitle());
                // 插入题目和比赛的关联信息
                contestMapper.insertProblem(contestProblem);
            }
        }
    }

    /**
     * 更新比赛状态
     * @param id
     * @param status
     */
    public void updateStatus(Integer id, Integer status) {
        // 更新比赛状态
        contestMapper.updateStatus(id, status);
        // 如果status=1开发所有关联题目
        if (status == 1) {
            List<ContestProblem> problemList = contestMapper.getQuestions(id);
            if (problemList != null && !problemList.isEmpty()) {
                for (ContestProblem problem : problemList) {
                    // 获取题目id修改题目的is
                    problemMapper.updateProblemIsOpen(problem.getProblemId());
                }
            }
        }
    }

    /**
     * 通过比赛id获得题目
     */
    public List<ContestProblem> getCompetitionQuestions(Integer contestId) {
        return contestMapper.getQuestions(contestId);
    }

    /**
     * 通过比赛id获得题目
     */
    public List<User> selectAllUser(Integer contestId) {
        // 获取该比赛的所有用户ID
        List<Integer> userIds = contestMapper.getUserIdsByContestId(contestId);
        // 获取这些用户的详细信息
        List<User> users = userMapper.getUsersByIds(userIds);
        return users;
    }


    /***
     * 添加比赛时候提交题目时候的数据
     */
    public void insertContestSubmission(Integer contestId, Integer problemId, Integer userId, boolean ac, LocalDateTime submitTime) {
        int isCorrect = 0;
        if(ac) isCorrect =1;
        ContestSubmission contestSubmission = new ContestSubmission();
        contestSubmission.setSubmitTime(submitTime);
        contestSubmission.setUserId(userId);
        contestSubmission.setProblemId(problemId);
        contestSubmission.setContestId(contestId);
        contestSubmission.setIsCorrect(isCorrect);
        contestMapper.insertContestSubmission(contestSubmission);
        if (ac) { contestMapper.updateAccept(contestId, problemId); }
        else { contestMapper.updateSubmit(contestId, problemId); }
    }

    public List<ContestSubmission> selectAllSubmission(Integer contestId) {
        return contestMapper.selectAllSubmission(contestId);
    }

    public SubmissionResult  findSubmissionByUserAndProblem(Integer contestId, Integer problemId, Integer userId, LocalDateTime contestStartTime) {
        List<ContestSubmission> contestSubmissions = contestMapper.findByContestProblemAndUser(contestId, problemId, userId);
        SubmissionResult submissionResult = new SubmissionResult();
        if (contestSubmissions == null || contestSubmissions.isEmpty()) {
            submissionResult.setSubmitTimes((long)0);
            submissionResult.setTimeUsage((long)-1);
            return submissionResult;
        }
        long submitCount = 0;  // 提交次数（包括AC）
        long totalTime = -1;  // 总耗时（如果没有AC则返回-1）
        int acSubmitIndex = -1;  // 第一个AC的索引，-1表示没有AC
        // 将比赛开始时间转换为Epoch秒
        long contestStartEpoch = contestStartTime.toEpochSecond(ZoneOffset.UTC);

        // 遍历所有提交记录，统计提交次数并判断是否有AC
        for (int i = 0; i < contestSubmissions.size(); i++) {
            ContestSubmission submission = contestSubmissions.get(i);
            submitCount++;  // 每次提交都会增加次数
            // 如果已经通过并且是第一次AC
            if (submission.getIsCorrect() == 1 && acSubmitIndex == -1) {
                acSubmitIndex = i;  // 记录第一次AC提交的索引
                // 获取AC时的提交时间，转换为Epoch秒
                LocalDateTime acSubmitTime = submission.getSubmitTime();
                long acTime = acSubmitTime.toEpochSecond(ZoneOffset.UTC);
                // 罚时计算：第一次AC前提交次数 * 20 + AC提交时的时间 - 比赛开始时间
                long penaltyTime = (submitCount - 1) * 20 + (acTime - contestStartEpoch);
                totalTime = penaltyTime;
            }
        }
        submissionResult.setSubmitTimes(submitCount);
        // 如果没有AC过
        if (acSubmitIndex == -1) submissionResult.setTimeUsage((long)-1);
        else submissionResult.setTimeUsage(totalTime);
        // 如果有AC，返回总提交次数和总时间
        return submissionResult;
    }

}
